<template>
  <div class="order-detail-container">
    <div class="page-header">
      <div class="header-title">
        <h2>订单详情</h2>
        <span class="subtitle">查看订单详细信息</span>
      </div>
      <div class="header-actions">
        <el-button @click="goBack">
          <el-icon><Back /></el-icon>返回列表
        </el-button>
        <el-button type="primary" @click="handlePrint">
          <el-icon><Printer /></el-icon>打印订单
        </el-button>
      </div>
    </div>

    <el-card v-loading="loading">
      <!-- 订单状态 -->
      <div class="order-status">
        <div class="status-tag">
          <el-tag :type="getStatusTag(order.status)" size="large">
            {{ getStatusLabel(order.status) }}
          </el-tag>
        </div>
        <el-steps :active="getStatusStep(order.status)" finish-status="success" simple>
          <el-step title="待审核" />
          <el-step title="已确认" />
          <el-step title="已分配" />
          <el-step title="运输中" />
          <el-step title="已完成" />
        </el-steps>
      </div>

      <!-- 订单基本信息 -->
      <el-descriptions title="订单信息" :column="3" border>
        <el-descriptions-item label="订单号" :span="2">{{ order.orderNo }}</el-descriptions-item>
        <el-descriptions-item label="订单类型">{{ getOrderTypeName(order.orderType) }}</el-descriptions-item>
        <el-descriptions-item label="客户名称" :span="2">{{ order.customer }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ order.createTime }}</el-descriptions-item>
        <el-descriptions-item label="预计提货时间">{{ order.expectedPickupTime }}</el-descriptions-item>
        <el-descriptions-item label="预计送达时间">{{ order.expectedDeliveryTime }}</el-descriptions-item>
        <el-descriptions-item label="订单金额">¥ {{ order.totalAmount.toFixed(2) }}</el-descriptions-item>
      </el-descriptions>

      <!-- 收发货信息 -->
      <el-row :gutter="20" class="address-info">
        <el-col :span="12">
          <el-card class="box-card">
            <template #header>
              <div class="card-header">
                <span>发货信息</span>
              </div>
            </template>
            <div class="address-content">
              <p><strong>发货人：</strong>{{ order.sender }}</p>
              <p><strong>联系电话：</strong>{{ order.senderPhone }}</p>
              <p><strong>发货地址：</strong>{{ order.fromAddress }}</p>
            </div>
          </el-card>
        </el-col>
        <el-col :span="12">
          <el-card class="box-card">
            <template #header>
              <div class="card-header">
                <span>收货信息</span>
              </div>
            </template>
            <div class="address-content">
              <p><strong>收货人：</strong>{{ order.receiver }}</p>
              <p><strong>联系电话：</strong>{{ order.receiverPhone }}</p>
              <p><strong>收货地址：</strong>{{ order.toAddress }}</p>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 货物信息 -->
      <div class="section-title">货物信息</div>
      <el-table :data="order.goods" border style="width: 100%">
        <el-table-column label="序号" type="index" width="50"></el-table-column>
        <el-table-column prop="name" label="货物名称" min-width="150"></el-table-column>
        <el-table-column prop="quantity" label="数量" width="100"></el-table-column>
        <el-table-column prop="weight" label="重量(kg)" width="100"></el-table-column>
        <el-table-column prop="volume" label="体积(m³)" width="100"></el-table-column>
        <el-table-column prop="packageType" label="包装方式" width="120">
          <template #default="scope">
            {{ getPackageTypeName(scope.row.packageType) }}
          </template>
        </el-table-column>
        <el-table-column prop="remarks" label="备注" min-width="150"></el-table-column>
      </el-table>

      <div class="goods-summary">
        <p>总数量: {{ totalQuantity }} 件</p>
        <p>总重量: {{ totalWeight.toFixed(2) }} kg</p>
        <p>总体积: {{ totalVolume.toFixed(2) }} m³</p>
      </div>

      <!-- 费用信息 -->
      <div class="section-title">费用信息</div>
      <el-descriptions :column="3" border>
        <el-descriptions-item label="计费方式">{{ getChargeTypeName(order.chargeType) }}</el-descriptions-item>
        <el-descriptions-item label="支付方式">{{ getPaymentMethodName(order.paymentMethod) }}</el-descriptions-item>
        <el-descriptions-item label="支付状态">
          <el-tag :type="order.paymentStatus === 'paid' ? 'success' : 'warning'">
            {{ order.paymentStatus === 'paid' ? '已支付' : '未支付' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="基础运费">¥ {{ order.basicFreight.toFixed(2) }}</el-descriptions-item>
        <el-descriptions-item label="装卸费">¥ {{ order.loadingFee.toFixed(2) }}</el-descriptions-item>
        <el-descriptions-item label="保险费">¥ {{ order.insuranceFee.toFixed(2) }}</el-descriptions-item>
        <el-descriptions-item label="其他费用">¥ {{ order.otherFees.toFixed(2) }}</el-descriptions-item>
        <el-descriptions-item label="费用说明" :span="2">{{ order.feeRemarks || '无' }}</el-descriptions-item>
        <el-descriptions-item label="订单总金额" :span="3" class="total-row">
          <span class="total-amount">¥ {{ order.totalAmount.toFixed(2) }}</span>
        </el-descriptions-item>
      </el-descriptions>

      <!-- 运输信息 -->
      <div v-if="['assigned', 'intransit', 'completed'].includes(order.status)" class="section-title">运输信息</div>
      <el-descriptions v-if="['assigned', 'intransit', 'completed'].includes(order.status)" :column="3" border>
        <el-descriptions-item label="承运商">{{ order.carrier }}</el-descriptions-item>
        <el-descriptions-item label="车牌号">{{ order.plateNumber }}</el-descriptions-item>
        <el-descriptions-item label="驾驶员">{{ order.driver }}</el-descriptions-item>
        <el-descriptions-item label="驾驶员电话">{{ order.driverPhone }}</el-descriptions-item>
        <el-descriptions-item label="实际提货时间" :span="2">{{ order.actualPickupTime || '未提货' }}</el-descriptions-item>
        <el-descriptions-item label="实际送达时间" :span="3">{{ order.actualDeliveryTime || '未送达' }}</el-descriptions-item>
      </el-descriptions>

      <!-- 运输轨迹 -->
      <div v-if="['intransit', 'completed'].includes(order.status)" class="section-title">运输轨迹</div>
      <div v-if="['intransit', 'completed'].includes(order.status)" class="track-timeline">
        <el-timeline>
          <el-timeline-item
            v-for="(track, index) in order.trackRecords"
            :key="index"
            :timestamp="track.time"
            :type="getTrackItemType(track.status)"
          >
            {{ track.description }}
            <div v-if="track.location" class="track-location">位置: {{ track.location }}</div>
          </el-timeline-item>
        </el-timeline>
      </div>

      <!-- 操作记录 -->
      <div class="section-title">操作记录</div>
      <el-table :data="order.operationLogs" border style="width: 100%">
        <el-table-column prop="time" label="操作时间" width="180"></el-table-column>
        <el-table-column prop="operator" label="操作人" width="120"></el-table-column>
        <el-table-column prop="action" label="操作类型" width="120">
          <template #default="scope">
            <el-tag>{{ scope.row.action }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="操作描述" min-width="200"></el-table-column>
        <el-table-column prop="remark" label="备注" min-width="150"></el-table-column>
      </el-table>

      <!-- 操作按钮 -->
      <div class="action-buttons">
        <el-button type="success" v-if="order.status === 'pending'" @click="handleApprove">审核通过</el-button>
        <el-button type="warning" v-if="order.status === 'confirmed'" @click="handleAssign">分配车辆</el-button>
        <el-button type="primary" v-if="order.status === 'assigned'" @click="handleStartTransport">开始运输</el-button>
        <el-button type="success" v-if="order.status === 'intransit'" @click="handleComplete">确认完成</el-button>
        <el-button type="danger" v-if="['pending', 'confirmed'].includes(order.status)" @click="handleCancel">取消订单</el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Back, Printer } from '@element-plus/icons-vue'

const router = useRouter()
const route = useRoute()

// 加载状态
const loading = ref(true)

// 订单数据
const order = ref({
  id: 1,
  orderNo: 'TMS-2025031401',
  orderType: 'normal',
  customer: '北京物流科技有限公司',
  customerId: 'customer1',
  fromAddress: '北京市朝阳区建国路88号',
  toAddress: '上海市浦东新区张江高科技园区',
  sender: '张三',
  senderPhone: '13800138000',
  receiver: '李四',
  receiverPhone: '13900139000',
  expectedPickupTime: '2025-03-15 09:00:00',
  expectedDeliveryTime: '2025-03-16 18:00:00',
  actualPickupTime: '',
  actualDeliveryTime: '',
  status: 'confirmed',
  totalAmount: 5800.00,
  createTime: '2025-03-14 10:15:22',
  chargeType: 'weight',
  basicFreight: 5000.00,
  loadingFee: 500.00,
  insuranceFee: 200.00,
  otherFees: 100.00,
  feeRemarks: '包含高速费用',
  paymentMethod: 'prepaid',
  paymentStatus: 'paid',
  carrier: '',
  plateNumber: '',
  driver: '',
  driverPhone: '',
  goods: [
    { 
      name: '电子设备', 
      quantity: 10, 
      weight: 500, 
      volume: 2,
      packageType: 'carton',
      remarks: '小心轻放'
    }
  ],
  trackRecords: [
    {
      time: '2025-03-14 10:15:22',
      status: 'created',
      description: '订单创建',
      location: '北京市朝阳区'
    },
    {
      time: '2025-03-14 11:30:45',
      status: 'confirmed',
      description: '订单审核通过',
      location: '北京市朝阳区'
    }
  ],
  operationLogs: [
    {
      time: '2025-03-14 10:15:22',
      operator: '系统',
      action: '创建',
      description: '订单创建成功',
      remark: ''
    },
    {
      time: '2025-03-14 11:30:45',
      operator: '管理员',
      action: '审核',
      description: '订单审核通过',
      remark: '正常订单'
    }
  ],
  remarks: '客户要求准时送达'
})

// 计算总数量
const totalQuantity = computed(() => {
  return order.value.goods.reduce((sum, item) => sum + (item.quantity || 0), 0)
})

// 计算总重量
const totalWeight = computed(() => {
  return order.value.goods.reduce((sum, item) => sum + (item.weight || 0), 0)
})

// 计算总体积
const totalVolume = computed(() => {
  return order.value.goods.reduce((sum, item) => sum + (item.volume || 0), 0)
})

// 获取状态标签样式
const getStatusTag = (status) => {
  const statusMap = {
    'pending': 'info',
    'confirmed': 'primary',
    'assigned': 'warning',
    'intransit': 'success',
    'completed': 'success',
    'cancelled': 'danger'
  }
  return statusMap[status] || 'info'
}

// 获取状态标签文本
const getStatusLabel = (status) => {
  const statusMap = {
    'pending': '待审核',
    'confirmed': '已确认',
    'assigned': '已分配',
    'intransit': '运输中',
    'completed': '已完成',
    'cancelled': '已取消'
  }
  return statusMap[status] || '未知'
}

// 获取状态步骤
const getStatusStep = (status) => {
  const statusStepMap = {
    'pending': 0,
    'confirmed': 1,
    'assigned': 2,
    'intransit': 3,
    'completed': 4,
    'cancelled': 0
  }
  return statusStepMap[status] || 0
}

// 获取订单类型名称
const getOrderTypeName = (type) => {
  const typeMap = {
    'normal': '普通运输',
    'express': '快速运输',
    'cold': '冷链运输',
    'dangerous': '危险品运输'
  }
  return typeMap[type] || '未知'
}

// 获取包装方式名称
const getPackageTypeName = (type) => {
  const typeMap = {
    'carton': '纸箱',
    'wooden': '木箱',
    'pallet': '托盘',
    'bag': '袋装',
    'bulk': '散装'
  }
  return typeMap[type] || '未知'
}

// 获取计费方式名称
const getChargeTypeName = (type) => {
  const typeMap = {
    'weight': '按重量计费',
    'volume': '按体积计费',
    'distance': '按距离计费',
    'fixed': '固定费用'
  }
  return typeMap[type] || '未知'
}

// 获取支付方式名称
const getPaymentMethodName = (method) => {
  const methodMap = {
    'prepaid': '预付款',
    'cod': '到付',
    'credit': '账期结算'
  }
  return methodMap[method] || '未知'
}

// 获取轨迹项类型
const getTrackItemType = (status) => {
  const typeMap = {
    'created': 'info',
    'confirmed': 'primary',
    'assigned': 'warning',
    'pickup': 'success',
    'intransit': 'success',
    'delivery': 'success',
    'completed': 'success',
    'exception': 'danger'
  }
  return typeMap[status] || 'info'
}

// 返回列表
const goBack = () => {
  router.push('/order')
}

// 打印订单
const handlePrint = () => {
  window.print()
}

// 审核通过
const handleApprove = () => {
  ElMessageBox.confirm(
    `确定要审核通过订单 "${order.value.orderNo}" 吗？`,
    '审核确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // 实际应用中应该调用API更新订单状态
    order.value.status = 'confirmed'
    
    // 添加操作记录
    order.value.operationLogs.push({
      time: new Date().toLocaleString(),
      operator: '当前用户',
      action: '审核',
      description: '订单审核通过',
      remark: ''
    })
    
    // 添加轨迹记录
    order.value.trackRecords.push({
      time: new Date().toLocaleString(),
      status: 'confirmed',
      description: '订单审核通过',
      location: '系统'
    })
    
    ElMessage.success('订单审核通过')
  }).catch(() => {
    // 取消审核
  })
}

// 分配车辆
const handleAssign = () => {
  router.push(`/order/assign/${order.value.id}`)
}

// 开始运输
const handleStartTransport = () => {
  ElMessageBox.confirm(
    `确定要开始运输订单 "${order.value.orderNo}" 吗？`,
    '确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // 实际应用中应该调用API更新订单状态
    order.value.status = 'intransit'
    order.value.actualPickupTime = new Date().toLocaleString()
    
    // 添加操作记录
    order.value.operationLogs.push({
      time: new Date().toLocaleString(),
      operator: '当前用户',
      action: '开始运输',
      description: '订单开始运输',
      remark: ''
    })
    
    // 添加轨迹记录
    order.value.trackRecords.push({
      time: new Date().toLocaleString(),
      status: 'pickup',
      description: '货物已提货',
      location: order.value.fromAddress
    })
    
    ElMessage.success('订单已开始运输')
  }).catch(() => {
    // 取消操作
  })
}

// 确认完成
const handleComplete = () => {
  ElMessageBox.confirm(
    `确定要完成订单 "${order.value.orderNo}" 吗？`,
    '确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // 实际应用中应该调用API更新订单状态
    order.value.status = 'completed'
    order.value.actualDeliveryTime = new Date().toLocaleString()
    
    // 添加操作记录
    order.value.operationLogs.push({
      time: new Date().toLocaleString(),
      operator: '当前用户',
      action: '完成',
      description: '订单已完成',
      remark: ''
    })
    
    // 添加轨迹记录
    order.value.trackRecords.push({
      time: new Date().toLocaleString(),
      status: 'completed',
      description: '货物已送达，订单完成',
      location: order.value.toAddress
    })
    
    ElMessage.success('订单已完成')
  }).catch(() => {
    // 取消操作
  })
}

// 取消订单
const handleCancel = () => {
  ElMessageBox.confirm(
    `确定要取消订单 "${order.value.orderNo}" 吗？`,
    '取消确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    // 实际应用中应该调用API更新订单状态
    order.value.status = 'cancelled'
    
    // 添加操作记录
    order.value.operationLogs.push({
      time: new Date().toLocaleString(),
      operator: '当前用户',
      action: '取消',
      description: '订单已取消',
      remark: ''
    })
    
    ElMessage.success('订单已取消')
  }).catch(() => {
    // 取消操作
  })
}

onMounted(() => {
  // 获取订单ID
  const orderId = route.params.id
  
  // 实际应用中应该调用API获取订单详情
  setTimeout(() => {
    // 模拟API调用
    loading.value = false
  }, 500)
})
</script>

<style scoped>
.order-detail-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-title {
  display: flex;
  flex-direction: column;
}

.header-title h2 {
  margin: 0;
  font-size: 22px;
  color: #303133;
}

.subtitle {
  font-size: 14px;
  color: #909399;
  margin-top: 5px;
}

.order-status {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f8f8f8;
  border-radius: 4px;
}

.status-tag {
  margin-right: 30px;
}

.section-title {
  font-size: 18px;
  font-weight: bold;
  margin: 30px 0 15px;
  color: #303133;
  border-left: 4px solid #409EFF;
  padding-left: 10px;
}

.address-info {
  margin: 20px 0;
}

.address-content p {
  margin: 10px 0;
  color: #606266;
}

.goods-summary {
  margin-top: 20px;
  text-align: right;
  font-size: 14px;
  color: #606266;
}

.total-amount {
  font-size: 24px;
  font-weight: bold;
  color: #f56c6c;
}

.total-row {
  background-color: #f8f8f8;
}

.track-timeline {
  margin: 20px 0;
  padding: 20px;
  background-color: #f8f8f8;
  border-radius: 4px;
}

.track-location {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

.action-buttons {
  margin-top: 30px;
  display: flex;
  justify-content: center;
  gap: 20px;
}

@media print {
  .header-actions, .action-buttons {
    display: none;
  }
}
</style>
